<template>
  <div class="selectResult">
    <el-dialog
      v-model="confrimWindowShow"
      :close-on-click-modal="false"
      title="查询结果如下:"
      width="100%"
      :show-close="true"
      :before-close="close"
    >
      <template #footer>
        <span class="dialog-footer">
          <div class="resultList">
            <div
              v-for="(data, index) in resultList"
              :key="index"
              @click="!shuntFlag ? toDetail(data.id) : landUseSearch(data.id)"
            >
              <img src="@/assets/images/icon/selectResult/结果.png" />
              <span>{{ data.name }}</span>
            </div>
          </div>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
import { getCurrentInstance, onMounted } from "vue";
import pubsub from "pubsub-js";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import axios from "axios";

import { polygonSelect } from "@/components/SpatialQuery/polygon.js";
import urlList from "@/store/urlList.json";
import message from "@/components/Message/showMessage";
import layerKeyList from "@/store/layerKeyList.json";

export default {
  name: "查询结果页面",
  data() {
    return {
      subList: [],
      confrimWindowShow: true,
      resultList: [],
      shuntFlag: 0,
      fromPath: "",
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const route = useRoute();
    const router = useRouter();

    onMounted(() => {
      subscribeList();
      // 分流
      proxy.shuntFlag = route.query.shunt === "polygonSelection" ? 0 : 1;
      switch (route.query.shunt) {
        case "polygonSelection":
          polygonSelection();
          break;
        case "landuseSelection":
          landuseSelection();
          break;
      }
    });

    // pubsub订阅列表
    function subscribeList() {
      proxy.subList.push(
        // 从详细信息页面返回
        pubsub.subscribe("toSelectResult", (n, data) => {
          proxy.confrimWindowShow = true;
        }),
        // 用地图层点选查询
        pubsub.subscribe("landuseClickSearch", (n, data) => {
          landuseSelection();
        })
      );
    }

    // 框选查询总起
    function polygonSelection() {
      // 框选查询
      getVertex()
        .then((res) => {
          return spatialAnalyse(res, StringToPointList(route.query.geometry));
        })
        .then((res) => {
          console.log(res);
          if (res.length > 0) {
            proxy.resultList = res;
            mapReset(res);
          } else {
            message("无查询结果,请重试", "error");
            router.push({
              path: "/mapLayout",
            });
          }
        });
    }

    // 查询所有标绘的所有端点
    function getVertex() {
      return axios({
        method: "get",
        url: urlList.serverURL + "getVertex",
      });
    }

    // 读取查询多边形端点列表
    function StringToPointList(string) {
      let pointList = [];
      let list = string.split(",");
      for (let i = 0; i < list.length; i++) {
        if (i % 2 === 0) {
          pointList.push([Number(list[i]), Number(list[i + 1])]);
        }
      }
      //   console.log(pointList);
      return pointList;
    }

    // 求算处于查询多边形中的标绘
    function spatialAnalyse(res, pointList) {
      return new Promise((resolve, reject) => {
        let selectedDrawing = [];
        res.data.result.forEach((element) => {
          // 点标绘
          if (element.featureType === "point") {
            let geometry = JSON.parse(element.geometry);
            //  使用polygonSelect类判断相交
            let SpatialQuery = new polygonSelect(pointList, geometry);
            if (SpatialQuery.main()) selectedDrawing.push(element);
          }
          // 面标绘
          else {
            // 整理点集
            let geometry = StringToPointList(element.geometry);
            //  使用polygonSelect类判断相交
            let SpatialQuery = new polygonSelect(pointList, geometry);
            if (SpatialQuery.main()) selectedDrawing.push(element);
          }
        });
        resolve(selectedDrawing);
      });
    }

    // 地图标绘重置
    function mapReset(list) {
      // 通知地图主页,仅显示选中的标绘
      pubsub.publish("mapDrawingReset", list);
      // 求算选区的中心
      let centerPoint = calculatingCenter(route.query.geometry.split(","));
      pubsub.publish("setView", centerPoint);
    }

    function calculatingCenter(list) {
      let latSum = 0;
      let lngSum = 0;
      for (let i = 0; i < list.length; i++) {
        if (i % 2 === 0) {
          latSum += Number(list[i]);
        } else {
          lngSum += Number(list[i]);
        }
      }
      return [latSum / (list.length / 2), lngSum / (list.length / 2)];
    }

    // 用地图层总起
    function landuseSelection() {
      // 读取查询结果
      let dataList = JSON.parse(route.query.layerList);
      // 载入DOM
      proxy.resultList = [];
      dataList.forEach((data) => {
        proxy.resultList.push({
          name: data,
          id: data,
        });
      });
    }

    // 用地地图arcgisserver查询
    function landUseSearch(layerName) {
      let selectedPoint = route.query.selectedPoint;
      // 查询arcgisserver
      let dataList = [];
      let rangeList = [];
      axios({
        method: "get",
        url: urlList.mapURL + layerName + "/MapServer/identify",
        params: {
          geometry: selectedPoint[1] + "," + selectedPoint[0],
          geometryType: "esriGeometryPoint",
          tolerance: 2,
          mapExtent: "45330.913495,171563.757422,80595.887643,203928.9151",
          imageDisplay: "60055096",
          f: "json",
        },
      }).then((res) => {
        if (res.data.results.length === 0) {
          message("无查询结果", "error");
          return;
        }
        // 根据图层名读取图层属性名列表
        let keyList = layerKeyList[res.data.results[0].layerName];
        let result = res.data.results[0].attributes;
        // 读取坐标点
        rangeList = res.data.results[0].geometry.rings;
        // 读取属性
        keyList.forEach((element) => {
          dataList.push({
            key: element.value,
            value: result[element.key],
          });
        });
        // console.log(result);
        // 用地查询数据分发
        landuseDataDispatch(dataList, rangeList);
      });
    }

    // 用地查询数据分发
    function landuseDataDispatch(dataList, rangeList) {
      proxy.confrimWindowShow = false;
      // 属性数据
      router.push({
        path: "/mapLayout/detail",
        query: { dataList: JSON.stringify(dataList), type: "landuseSelect" },
      });
      // 边界点数据
      pubsub.publish("drawLanduseBound", { list: rangeList, isOn: true });
    }

    //  跳转至详细信息界面
    function toDetail(id) {
      if (event.target.children.length > 0) {
        // let id = Array.from(event.target.children)[2].innerHTML;
        proxy.confrimWindowShow = false;
        // 路由跳转
        router.push({
          path: "/mapLayout/detail",
          query: { id, geometry: route.query.geometry, type: "polygonSelect" },
        });
      }
    }

    // 返回地图主页
    function close() {
      // console.log("####");
      router.push({
        path: "/mapLayout",
      });
      pubsub.publish("mapReset");
    }

    return { toDetail, close, landUseSearch };
  },
  watch: {
    resultList: {
      handler(newValue) {
        if (!(newValue.length > 1) && this.fromPath != "/mapLayout/detail") {
          this.landUseSearch(newValue[0].id);
        }
      },
      deep: true,
      // immediate: true,
    },
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.fromPath = from.path;
    });
  },
  beforeDestroy() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
  beforeRouteLeave() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
};
</script>

<style lang="less" scoped>
.resultList {
  > div {
    text-align: left;
    border-radius: 5px;
    padding: 2%;
    > img {
      width: 10%;
      margin-right: 2%;
      margin-bottom: 2px;
    }
    > span {
      font-size: 120%;
    }
  }
  > div:hover {
    background-color: rgb(247, 247, 247);
  }
}
</style>